<script lang="ts" setup>
import { getCurrentInstance, ref, inject } from 'vue'
import { onLoad, onPageScroll, onReady, onShow } from '@dcloudio/uni-app'
import TnLineProgress from '@tuniao/tnui-vue3-uniapp/components/line-progress/src/line-progress.vue'
import TnPicker from '@tuniao/tnui-vue3-uniapp/components/picker/src/picker.vue'
import TnDateTimePicker from '@tuniao/tnui-vue3-uniapp/components/date-time-picker/src/date-time-picker.vue'
import { addPlanApi, delPlansApi, updatePlanApi } from '@/services/api'
const openPicker = ref(false)
const planDetail = ref()
const wordAll = ref() //每天单词数
const needDay = ref() //需要天数
const morningLearnSum = ref() //早上听的数量
const nightLearnSum = ref() //晚上听的数量
const toMyInterview = async () => {
  if (!checking()) {
    return false
  }
  const mV = removeLeadingZerosFromTime(mTimeValue.value)
  const eV = removeLeadingZerosFromTime(eTimeValue.value)
  const params = {
    bookId: planDetail.value.bookId,
    learnType: planDetail.value.learnType,
    morningStudyInfo: {
      learnTime: mV,
      morningLearnSum: wordNumber.value[pickerValue.value[0]],
    },
    nightStudyInfo: {
      learnTime: eV,
      nightLearnSum: wordNumber.value[pickerValue.value[1]],
    },
    perDayNum: wordAll.value,
    repeatTimes: repeatTimes.value,
    scenseType: planDetail.value.scenseType,
  }
  //已经完成需要重新制定计划
  if (ifFinish.value == 1) {
    //清空计划之后新增计划
    const res = await delPlans()
    if (res) {
      //新增
      const data = await addPlanApi(params)
      if (data.code === 200) {
        uni.showToast({
          title: '重新制定计划成功',
          icon: 'none',
        })
        uni.navigateBack({
          delta: 1,
        })
      }
    }
  } else {
    if (planDetail.value.planId) {
      params.planId = planDetail.value.planId
      console.log(params)
      console.log('更新')
      //更新
      const data = await updatePlanApi(params)
      if (data.code === 200) {
        uni.showToast({
          title: '更新成功',
          icon: 'none',
        })
        uni.navigateBack({
          delta: 1,
        })
      }
    } else {
      console.log('新增')
      console.log(params)
      //新增
      const data = await addPlanApi(params)
      if (data.code === 200) {
        uni.showToast({
          title: '计划添加成功',
          icon: 'none',
        })
        uni.navigateBack({
          delta: 1,
        })
      }
    }
  }

  console.log('params', params)
}
//清空计划之后新增计划
const delPlans = async () => {
  const data = await delPlansApi({
    planIds: [
      planDetail.value.morningStudyInfo.planId,
      planDetail.value.nightStudyInfo.planId,
    ],
  })
  if (data.code === 200) {
    console.log('清楚计划成功，请制定计划')
    return true
  }
}
//校验不为空
const checking = () => {
  if (!wordAll.value) {
    uni.showToast({
      title: `请选择每天${
        planDetail.value.learnType == 1
          ? '单词'
          : planDetail.value.learnType == 2
            ? '句子'
            : planDetail.value.learnType == 3
              ? '课文'
              : ''
      }数`,
      icon: 'none',
    })
    return false
  }
  if (!mTimeValue.value) {
    uni.showToast({
      title: '请选择早上开始时间',
      icon: 'none',
    })
    return false
  }
  if (!eTimeValue.value) {
    uni.showToast({
      title: '请选择晚上开始时间',
      icon: 'none',
    })
    return false
  }
  if (!numberValue.value) {
    uni.showToast({
      title: '请选择循环次数',
      icon: 'none',
    })
    return false
  }
  return true
}
//移除时间格式的前导0
const removeLeadingZerosFromTime = (timeStr) => {
  const str = timeStr.split(':').map((item, index) => {
    // 使用正则表达式匹配前导零，并用空字符串替换它们
    if (item[0] == '0') {
      return item.slice(1)
    }
    return item
  })
  console.log(str.join(':'))
  return str.join(':')
}
//添加时间格式的前导0
const addLeadingZerosFromTime = (timeStr) => {
  const str = timeStr.split(':').map((item, index) => {
    // 使用正则表达式匹配前导零，并用空字符串替换它们
    if (item.length == 1) {
      return '0' + item
    }
    return item
  })
  console.log(str.join(':'))
  return str.join(':')
}
const toShowSetWordPopup = () => {
  showSetWordPopup.value = true
}
const wordNumber = ref([5, 10, 15, 20, 25, 30, 35, 40, 45, 50])
const pickerValue = ref([] as any)
//剩余单词数
const wordNumberValue = ref(1000)
const needDate = ref()
const showSetWordPopup = ref(false)
const openMTimePicker = ref(false)
const mTimeValue = ref('06:00')
const openETimePicker = ref(false)
const eTimeValue = ref('18:00')
const openNumberDataPicker = ref(false)
const numberValue = ref('')
const repeatTimes = ref() //循环次数的index,不循环：0，反复循环-1
const numberData = [
  '不循环',
  '2遍',
  '3遍',
  '4遍',
  '5遍',
  '6遍',
  '7遍',
  '8遍',
  '9遍',
  '10遍',
  '反复循环，直到退出',
]
const ifFinish = ref(0)
const onPickerChange = (e) => {
  pickerValue.value = e.detail.value
  // wordAll.value =
  //   wordNumber.value[e.detail.value[0]] + wordNumber.value[e.detail.value[1]]
  setDate()
}
const onNumberDataPickerChange = (item) => {
  // numberValue.value = item
  // console.log(numberValue.value)
  // numberIndex = numberData.indexOf(item)
  // console.log(numberIndex)
  // // repeatTimes.value = numberData.length - 1 == index ? -1 : index
  console.log(repeatTimes.value)
}
onLoad((options) => {
  // removeLeadingZerosFromTime('08:00')
  console.log(options, 'options')
  if (options.ifFinish == 1) {
    ifFinish.value = 1
  }
  planDetail.value = options.data
    ? JSON.parse(decodeURIComponent(options.data))
    : null
  console.log(planDetail.value)
  // 如果存在计划planId，则显示计划详情
  if (planDetail.value.planId) {
    //早上跟晚上的单词数量
    morningLearnSum.value = planDetail.value.morningStudyInfo.morningLearnSum
    nightLearnSum.value = planDetail.value.nightStudyInfo.nightLearnSum
    const index1 = wordNumber.value.indexOf(morningLearnSum.value)
    const index2 = wordNumber.value.indexOf(nightLearnSum.value)
    pickerValue.value = [index1, index2]
    //计算每日读几个单词
    wordAll.value = morningLearnSum.value + nightLearnSum.value
    mTimeValue.value = addLeadingZerosFromTime(
      planDetail.value.morningStudyInfo.learnTime
    )
    eTimeValue.value = addLeadingZerosFromTime(
      planDetail.value.nightStudyInfo.learnTime
    )
    repeatTimes.value = planDetail.value.repeatTimes
    console.log(repeatTimes.value)
    if (repeatTimes.value > -1) {
      numberValue.value = numberData[repeatTimes.value]
      console.log(numberValue.value)
    } else {
      numberValue.value = '反复循环，直到退出'
    }
    setDate()
    console.log(mTimeValue.value, '2')
    console.log(eTimeValue.value, '3')
  } else {
    setTimeout(() => {
      pickerValue.value = [0, 0]
      wordAll.value =
        wordNumber.value[pickerValue.value[0]] +
        wordNumber.value[pickerValue.value[1]]
      setDate()
      eTimeValue.value = '18:00'
      mTimeValue.value = '06:00'
    }, 0)
    console.log(eTimeValue.value, '666666')
  }
})
const canale = () => {
  showSetWordPopup.value = false
}
const commit = () => {
  wordAll.value =
    wordNumber.value[pickerValue.value[0]] +
    wordNumber.value[pickerValue.value[1]]
  showSetWordPopup.value = false
}
const numberCancel = () => {
  openNumberDataPicker.value = false
}
const numberConfirm = (item) => {
  numberValue.value = item
  console.log(numberValue.value)
  const index = numberData.indexOf(item)
  repeatTimes.value = numberData.length - 1 == index ? -1 : index
  openNumberDataPicker.value = false
}
const toShowMTimePicker = () => {
  openMTimePicker.value = true
}
const toShowETimePicker = () => {
  openETimePicker.value = true
}
const toShowNumberDataPicker = () => {
  openNumberDataPicker.value = true
}
//将时间戳转为日期的函数
const formatTimestampToDate = (timestamp) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}
const setDate = () => {
  //计算需要的天数
  needDay.value = Math.ceil(
    (planDetail.value.lessonSum - planDetail.value.hadLearnSum) /
      (wordNumber.value[pickerValue.value[0]] +
        wordNumber.value[pickerValue.value[1]])
  )
  //当前日期加上完成天数的时间戳
  needDate.value = formatTimestampToDate(
    new Date().getTime() + needDay.value * 86400000
  )
}
</script>

<template>
  <view class="contain">
    <view class="main_box_list">
      <view class="bookStyleBox">
        <view class="bookImg">
          <image :src="planDetail.bookUrl" />
        </view>
        <view class="right_box">
          <view class="title_Line">
            <view class="title"> {{ planDetail.title }} </view>
          </view>
          <view class="right_text">
            每日{{ wordAll ? wordAll : '/' }}个，剩余{{
              needDay ? needDay : '/'
            }}天
          </view>

          <view class="progress">
            <TnLineProgress
              :percent="(planDetail.hadLearnSum / planDetail.lessonSum) * 100"
              active-color="#3388FF"
              height="10"
            />
          </view>
          <view class="text_number">
            {{ planDetail.hadLearnSum }}/{{ planDetail.lessonSum }}
          </view>
        </view>
      </view>
    </view>
    <view class="setting_list_box">
      <view class="line_box" @tap="toShowSetWordPopup">
        <view class="text">
          每天听{{
            planDetail.learnType == 1
              ? '单词'
              : planDetail.learnType == 2
                ? '句子'
                : planDetail.learnType == 3
                  ? '课文'
                  : ''
          }}
        </view>
        <view class="right_box">
          <view class="main_text">
            {{ wordAll ? wordAll : '请选择数量' }}
          </view>
          <TnIcon name="right" color="#333333" size="30rpx" />
        </view>
      </view>
      <view class="line_box" @tap="toShowMTimePicker">
        <view class="text"> 早上开始时间 </view>
        <view class="right_box">
          <view class="main_text">
            {{ mTimeValue ? mTimeValue : '请选择' }}
          </view>
          <TnIcon name="right" color="#333333" size="30rpx" />
        </view>
      </view>
      <view class="line_box" style="border: none" @tap="toShowETimePicker">
        <view class="text"> 晚上开始时间 </view>
        <view class="right_box">
          <view class="main_text">
            {{ eTimeValue ? eTimeValue : '请选择' }}
          </view>
          <TnIcon name="right" color="#333333" size="30rpx" />
        </view>
      </view>
    </view>
    <view class="setting_number_line">
      <view class="line_box" @tap="toShowNumberDataPicker">
        <view class="text"> 循环次数 </view>
        <view class="right_box">
          <view class="main_text">
            {{ numberValue ? numberValue : '请选择' }}
          </view>
          <TnIcon name="right" color="#333333" size="30rpx" />
        </view>
      </view>
    </view>
    <TnPopup v-model="showSetWordPopup" open-direction="bottom">
      <view class="setting">
        <view class="top_btn">
          <view class="left" @tap="canale"> 取消 </view>
          <view class="right" @tap="commit"> 确定 </view>
        </view>
        <view class="title">
          预计完成日期：
          <text>{{ needDate }}</text>
        </view>
        <view class="setting_box">
          <view class="title_box">
            <view class="text">
              每天早上听{{
                planDetail.learnType == 1
                  ? '单词'
                  : planDetail.learnType == 2
                    ? '句子'
                    : planDetail.learnType == 3
                      ? '课文'
                      : ''
              }}</view
            >
            <view class="text">
              每天晚上听{{
                planDetail.learnType == 1
                  ? '单词'
                  : planDetail.learnType == 2
                    ? '句子'
                    : planDetail.learnType == 3
                      ? '课文'
                      : ''
              }}
            </view>
          </view>

          <view class="set_box">
            <picker-view
              :value="pickerValue"
              class="picker-view"
              indicator-class="picker-view-column"
              @change="onPickerChange"
            >
              <picker-view-column>
                <view
                  class="item"
                  v-for="(item, index) in wordNumber"
                  :key="index"
                  >{{ item }}个</view
                >
              </picker-view-column>
              <picker-view-column>
                <view
                  class="item"
                  v-for="(item, index) in wordNumber"
                  :key="index"
                  >{{ item }}个</view
                >
              </picker-view-column>
            </picker-view>
          </view>
        </view>
      </view>
    </TnPopup>
    <TnDateTimePicker
      v-model="mTimeValue"
      v-model:open="openMTimePicker"
      mode="timeNoSecond"
      :init-current-date-time="false"
    />
    <TnDateTimePicker
      v-model="eTimeValue"
      v-model:open="openETimePicker"
      mode="timeNoSecond"
    />
    <TnPicker
      v-model="numberValue"
      v-model:open="openNumberDataPicker"
      :data="numberData"
      @change="onNumberDataPickerChange"
      @confirm="numberConfirm"
      @cancel="numberCancel"
    />
    <view class="btn">
      <TnButton
        bg-color="#5155E6"
        text-color="#fff"
        width="100%"
        height="80rpx"
        font-size="36rpx"
        @tap="toMyInterview"
        >保存计划</TnButton
      >
    </view>
  </view>
</template>

<style lang="scss" scoped>
.contain {
  width: 100%;
  padding: 20rpx 32rpx;
  .main_box_list {
    width: 100%;
    background: #fff;
    border-radius: 20rpx;
    padding: 32rpx 32rpx 0;
    margin-top: 32rpx;
    margin-bottom: 32rpx;
    .bookStyleBox {
      width: 100%;
      display: flex;
      padding-bottom: 32rpx;
      .bookImg {
        width: 120rpx;
        height: 180rpx;
        object-fit: contain;
        margin-right: 20rpx;
      }
      .right_box {
        flex: 1;
        .title_Line {
          width: 100%;
          display: flex;
          justify-content: space-between;
          .title {
            font-size: 36rpx;
            color: #101010;
          }
        }
        .right_text {
          font-size: 26rpx;
          color: #000000;
          font-weight: bold;
          margin: 8rpx 0;
        }
        .progress {
          margin: 16rpx 0;
        }
        .text_number {
          color: #6c6c6c;
          font-size: 28rpx;
        }
      }
    }
  }
  .setting_list_box {
    width: 100%;
    background: #fff;
    padding: 20rpx 32rpx;
    margin: 50rpx 0 30rpx;
    border-radius: 20rpx;
    .line_box {
      width: 100%;
      border-bottom: 2rpx solid #e8e8e8;
      display: flex;
      padding: 0 10rpx;
      justify-content: space-between;
      align-items: center;
      height: 80rpx;
      .text {
        font-size: 28rpx;
        color: #000000;
      }
      .right_box {
        display: flex;
        align-items: center;
        color: #6c6c6c;
        font-size: 24rpx;
        height: 80rpx;
        .main_text {
          margin-right: 10rpx;
        }
      }
    }
  }
  .setting_number_line {
    width: 100%;
    background: #fff;
    padding: 20rpx 32rpx;
    border-radius: 20rpx;
    .line_box {
      width: 100%;
      display: flex;
      padding: 0 10rpx;
      justify-content: space-between;
      align-items: center;
      height: 80rpx;
      .text {
        font-size: 28rpx;
        color: #000000;
      }
      .right_box {
        display: flex;
        align-items: center;
        color: #6c6c6c;
        font-size: 24rpx;
        height: 80rpx;
        .main_text {
          margin-right: 10rpx;
        }
      }
    }
  }
  .setting {
    .top_btn {
      height: 80rpx;
      border-bottom: 2rpx solid #e8e8e8;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 32rpx;
      .left {
        font-size: 28rpx;
        color: #ff444f;
      }
      .right {
        color: #01beff;
        font-size: 28rpx;
      }
    }
    .title {
      font-size: 24rpx;
      color: #101010;
      font-weight: bold;
      padding: 20rpx;
      text {
        color: #0f40f5;
      }
    }
    .setting_box {
      width: 100%;
      background: #fff;
      margin-top: 30rpx;
      border-radius: 20rpx;
      padding: 0 32rpx;
      .title_box {
        border-bottom: 2rpx solid #e8e8e8;
        display: flex;
        justify-content: space-between;
        height: 90rpx;
        .text {
          width: 50%;
          text-align: center;
          line-height: 90rpx;
          font-size: 28rpx;
          font-weight: bold;
        }
      }
      .set_box {
        padding: 0 10rpx;
        .picker-view {
          width: 100%;
          height: 300rpx;
          margin-top: 20rpx;
        }
        .item {
          line-height: 68rpx;
          text-align: center;
        }
        :deep(.picker-view-column) {
          background: #3388ff;
          opacity: 0.3;
          color: #000000;
          font-weight: bold;
          font-size: 40rpx;
          border-radius: 10rpx;
        }
      }
    }
  }
  .btn {
    padding: 0 32rpx;
    width: 100%;
    position: fixed;
    bottom: 10rpx;
    left: 0;
  }
}
</style>
